package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        String pwd = DigestUtils.md5DigestAsHex(password.getBytes());

        if (!pwd.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }


    /**
     * 新增员工功能
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public Result insertEmp(EmployeeDTO dto) {
        //先非空判断，再判断用户名是否已经存在
        if (dto.getUsername() == null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //调用mapper的方法来查询用户名是否已经存在
        Employee employee = employeeMapper.getByUsername(dto.getUsername());
        if (employee != null){
            return Result.error(MessageConstant.USERNAME_EXIST);
        }
        employee = new Employee();
        //将dto的内容复制到emp
        BeanUtils.copyProperties(dto,employee);
        //设置密码 并且加密 默认值：123456
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        //设置账号状态 默认值：1
        employee.setStatus(StatusConstant.ENABLE);
        //设置创建修改时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //设计修改人和修改人id
        Long currentId = BaseContext.getCurrentId();

        employee.setCreateUser(currentId);
        employee.setUpdateUser(currentId);
        //调用mapper方法
        employeeMapper.insertEmp(employee);

        return Result.success();
    }

    //分页查询
    @Override
    public Result pageQuery(EmployeePageQueryDTO dto) {
        //判断是否为空，如果为空的话就设置每页显示多少个
        if (dto.getPage() == null){
            dto.setPage(1);
        }
        if (dto.getPageSize() == null){
            dto.setPageSize(5);
        }

        //使用PageHelper分页  PageHelper.startPage(页码 , 每页显示数量);
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        //调用mapper根据条件查询员工
        Page<Employee> page = employeeMapper.pageQuery(dto);
        //
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(page.getResult());
        //返回数据
        return Result.success(pageResult);
    }


    //修改员工禁止启用状态
    @Override
    public Result updateEmpStatus(Integer status, Long id) {
        //先判断是否为空
        if (id == null){
            return Result.error(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //创建一个对象
        Employee employee = new Employee();
        employee.setStatus(status);
        employee.setId(id);
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());
        //调用mapper的方法进行查询
        employeeMapper.updateEmp(employee);
        //返回
        return Result.success();
    }

    @Override
    public Result selectById(Long id) {
        if (id == null){
            return Result.error(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        Employee employee = employeeMapper.selectById(id);

        return Result.success(employee);
    }

    @Override
    public Result updateEmp(EmployeeDTO dto) {
        //判断是否为空
        if (dto.getId() == null){
            return Result.error(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //将内容复制到实体类中
        Employee employee = new Employee();
        BeanUtils.copyProperties(dto,employee);
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());
        //调用mapper方法
        employeeMapper.updateEmp(employee);
        return Result.success();
    }


}
